import { ForbiddenException, Injectable } from '@nestjs/common'
import { UserService } from '../user/user.service'
import { JwtService } from '@nestjs/jwt'

import * as argon2 from 'argon2'
@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService
  ) {}
  async signin(username: string, password: string) {
    const user = await this.userService.findByUsername(username)
    if (!user) {
      throw new ForbiddenException('用户不存在')
    }
    console.log(user.password, password)
    // 用户密码进行比对
    const isPasswordValid = await argon2.verify(user.password, password)
    if (!isPasswordValid) {
      throw new ForbiddenException('用户名或者密码错误')
    }
    const payload = { sub: user.id, username: user.username }
    return {
      access_token: await this.jwtService.signAsync(payload)
    }
  }
  signout() {
    return 'logout'
  }
}
